package dao

import (
	"context"
	"errors"
	"github.com/ecodeclub/ekit/syncx/atomicx"
)

type DoubleWriteDao struct {
	src     InteractiveDAO
	dst     InteractiveDAO
	pattern *atomicx.Value[string]
}

const (
	patternSrcOnly  = "SRC_ONLY"
	patternSrcFirst = "SRC_FIRST"
	patternDstOnly  = "DST_ONLY"
	patternDstFirst = "DST_FIRST"
)

func NewDoubleWriteDao(src InteractiveDAO, dst InteractiveDAO) *DoubleWriteDao {
	return &DoubleWriteDao{src: src, dst: dst, pattern: atomicx.NewValueOf(patternSrcOnly)}
}

func (d *DoubleWriteDao) IncrReadCnt(ctx context.Context, biz string, bizId int64) error {
	switch d.pattern.Load() {
	case patternSrcOnly:
		return d.src.IncrReadCnt(ctx, biz, bizId)
	case patternSrcFirst:
		err := d.src.IncrReadCnt(ctx, biz, bizId)
		if err != nil {
			return err
		}
		return d.dst.IncrReadCnt(ctx, biz, bizId)
	case patternDstOnly:
		return d.dst.IncrReadCnt(ctx, biz, bizId)
	case patternDstFirst:
		err := d.dst.IncrReadCnt(ctx, biz, bizId)
		if err != nil {
			return err
		}
		return d.src.IncrReadCnt(ctx, biz, bizId)
	default:
		return errors.New("未知的双写模式")
	}
}
